// src/stores/authStore.js
import {defineStore} from 'pinia'
import authData  from "@/mock/authData.js";

import {UserApi} from "@/api/user/index.js";
import { authApi } from '@/api/auth/index.js'; // 引入授权管理API

export const useAuthStore = defineStore('auth',{
    state:()=>({
        user:null,
        token:null,
        menuList:[],
        permissions:[],
        roles:[],
        realName: "系统管理员",
        deptId: 1,
        deptName: "总部",
        isAuthenticated:false,
        hasLoadedDynamicRoutes:false,
    }),
    actions:{
        async login(formData){

            const promise = await UserApi.login(formData);
            this.user  = promise.data.userEntity
            this.token = promise.data.token
            this.isAuthenticated = true
            //获取用户权限信息
            await this.getUserAuthInfo()

        },
        logout(){
            this.user = null
            this.isAuthenticated = false
            this.token = null
            this.menuList = []
            this.permissions = []
            this.hasLoadedDynamicRoutes = false
        },
        isLoggedIn(){
            return this.isAuthenticated
        },
        async getUserAuthInfo(){
            const userAuthInfo = await UserApi.getUserAuthInfo();
            this.menuList = userAuthInfo.data.menuTree
            this.permissions = userAuthInfo.data.permissions
            this.roles = userAuthInfo.data.roles
            this.realName = userAuthInfo.data.realName
            this.deptId = userAuthInfo.data.deptId
            this.deptName = userAuthInfo.data.deptName

        },
        
        // ==================== 授权管理功能 ====================
        
        // 为用户分配/取消分配角色
        async assignUserRoles(data) {
            try {
                const result = await authApi.assignRoles(data);
                // 如果操作成功，更新用户角色信息
                if (this.user && this.user.id === data.userId) {
                    this.roles = result.data.roles || [];
                }
                return result;
            } catch (error) {
                throw error;
            }
        },
        
        // 为角色分配/取消分配权限点
        async assignRoleAcls(data) {
            try {
                const result = await authApi.assignAcls(data);
                // 如果当前用户拥有该角色，更新权限信息
                if (this.roles.includes(data.roleId)) {
                    await this.getUserAuthInfo();
                }
                return result;
            } catch (error) {
                throw error;
            }
        },
        
        // 配置角色的数据权限范围
        async configureDataScope(data) {
            try {
                const result = await authApi.dataScope(data);
                // 如果当前用户拥有该角色，更新权限信息
                if (this.roles.includes(data.roleId)) {
                    await this.getUserAuthInfo();
                }
                return result;
            } catch (error) {
                throw error;
            }
        },
        
        // 查询用户权限（包含角色和权限点）
        async fetchUserPermissions(params) {
            try {
                const result = await authApi.getUserPermissions(params);
                return result;
            } catch (error) {
                throw error;
            }
        },
        
        // 刷新权限缓存
        async refreshAuthCache() {
            try {
                const result = await authApi.refreshCache();
                // 刷新成功后重新获取用户权限信息
                await this.getUserAuthInfo();
                return result;
            } catch (error) {
                throw error;
            }
        },
        
        // 获取权限回收操作记录
        async getPermissionRecycleLogs(params) {
            try {
                const result = await authApi.getRecycleLog(params);
                return result;
            } catch (error) {
                throw error;
            }
        }
    }
})
